﻿using Leeder.Logger;
using Leeder.Util.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using ThermalImagery.Comm;
using ThermalImagery.Model;

namespace ThermalImagery.Hik
{
    public class ThermAlarm
    {
        /// <summary>
        /// 是否相机断开重连
        /// </summary>
        public bool IsReconnectCheck { get; set; }
        /// <summary>
        /// 相机连接中断
        /// </summary>
        public event Action<string> OnConnectionBreak;
        /// <summary>
        /// 温度检测数据接收事件
        /// </summary>
        public event Action<AlarmInfoModel> DataReceiverEvent;
        /// <summary>
        /// 当前相机是否连接
        /// </summary>
        public bool IsConnection { get; set; }
        /// <summary>
        /// 日志
        /// </summary>
        public LogOperate LogObj => Log.GetLogger(this.GetType());

        private Int32 m_lUserID = -1;
        private Int32[] m_lAlarmHandle = new Int32[200];
        private Int32 iListenHandle = -1;
        private int iDeviceNumber = 0; //添加设备个数
        private int iFileNumber = 0; //保存的文件个数
        private uint iLastErr = 0;
        private string strErr;

        private Int32 m_lRealHandle = -1;
        CHCNetSDK.REALDATACALLBACK RealData = null;

        public CHCNetSDK.LOGINRESULTCALLBACK LoginCallBack = null;
        private CHCNetSDK.EXCEPYIONCALLBACK m_fExceptionCB = null;
        private CHCNetSDK.MSGCallBack_V31 m_falarmData_V31 = null;
        private CHCNetSDK.MSGCallBack m_falarmData = null;

        public delegate void UpdateTextStatusCallback(string strLogStatus, IntPtr lpDeviceInfo);
        public delegate void UpdateListBoxCallback(string strAlarmTime, string strDevIP, string strAlarmMsg);
        public delegate void UpdateListBoxCallbackException(string strAlarmTime, int lUserID, string strAlarmMsg);

        public string ListenIP = "";  //监听IP地址
        public string ListenPort = "7200";  //监听端口
        public string SteamID = "";
        public List<Int32> m_lUserIDList = new List<Int32>();
        public List<string> deviceIpList = new List<string>();
        public List<string> deviceStatusList = new List<string>();      

        /// <summary>
        /// 单例模式
        /// </summary>
        private static ThermAlarm instance = new ThermAlarm();
        public static ThermAlarm getInstance()
        {
            if (instance == null)
                instance = new ThermAlarm();
            return instance;
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        private ThermAlarm()
        {

        }

        /// <summary>
        /// SDK初始化
        /// </summary>
        /// <returns></returns>
        public bool Init(ref string errMess)
        {
            IsConnection = false;
            strErr = "";
            bool m_bInitSDK = CHCNetSDK.NET_DVR_Init();
            if (m_bInitSDK == false)
            {
                errMess = "热成像相机初始化失败!";
                return false;
            }
            else
            {
                byte[] strIP = new byte[16 * 16];
                uint dwValidNum = 0;
                Boolean bEnableBind = false;

                //获取本地PC网卡IP信息
                if (CHCNetSDK.NET_DVR_GetLocalIP(strIP, ref dwValidNum, ref bEnableBind))
                {
                    if (dwValidNum > 0)
                    {
                        //取第一张网卡的IP地址为默认监听端口
                        ListenIP = System.Text.Encoding.UTF8.GetString(strIP, 0, 16);
                        //CHCNetSDK.NET_DVR_SetValidIP(0,true); //绑定第一张网卡
                    }

                }

                //保存SDK日志 To save the SDK log
                CHCNetSDK.NET_DVR_SetLogToFile(3, ".\\SdkLog\\", true);

                //设置透传报警信息类型
                CHCNetSDK.NET_DVR_LOCAL_GENERAL_CFG struLocalCfg = new CHCNetSDK.NET_DVR_LOCAL_GENERAL_CFG();
                struLocalCfg.byAlarmJsonPictureSeparate = 1;//控制JSON透传报警数据和图片是否分离，0-不分离(COMM_VCA_ALARM返回)，1-分离（分离后走COMM_ISAPI_ALARM回调返回）

                Int32 nSize = Marshal.SizeOf(struLocalCfg);
                IntPtr ptrLocalCfg = Marshal.AllocHGlobal(nSize);
                Marshal.StructureToPtr(struLocalCfg, ptrLocalCfg, false);

                if (!CHCNetSDK.NET_DVR_SetSDKLocalCfg(17, ptrLocalCfg))  //NET_DVR_LOCAL_CFG_TYPE_GENERAL
                {
                    iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    strErr = "热成像相机初始化配置失败, 失败代码= " + iLastErr;
                    errMess = "热成像相机初始化配置失败, 失败代码= " + iLastErr; 
                    //MessageBox.Show(strErr);
                }
                Marshal.FreeHGlobal(ptrLocalCfg);

                for (int i = 0; i < 200; i++)
                {
                    m_lAlarmHandle[i] = -1;
                }

                //设置异常消息回调函数
                if (m_fExceptionCB == null)
                {
                    m_fExceptionCB = new CHCNetSDK.EXCEPYIONCALLBACK(cbExceptionCB);
                }
                CHCNetSDK.NET_DVR_SetExceptionCallBack_V30(0, IntPtr.Zero, m_fExceptionCB, IntPtr.Zero);


                //设置报警回调函数
                if (m_falarmData_V31 == null)
                {
                    m_falarmData_V31 = new CHCNetSDK.MSGCallBack_V31(MsgCallback_V31);
                }
                CHCNetSDK.NET_DVR_SetDVRMessageCallBack_V31(m_falarmData_V31, IntPtr.Zero);

                return true;
            }
        }

        /// <summary>
        /// 登录设备
        /// </summary>
        /// <param name="errMess"></param>
        /// <returns>登录设备（设备句柄，设备IP，设备状态）</returns>
        public bool Login(string deviceIp, string devicePort, string userName, string password,ref string errMess)
        {
            if (iDeviceNumber >= 20)
            {
                errMess = "本程序限制最多添加20台设备！";
                return false;
            }

            CHCNetSDK.NET_DVR_USER_LOGIN_INFO struLogInfo = new CHCNetSDK.NET_DVR_USER_LOGIN_INFO();

            //设备IP地址或者域名
            byte[] byIP = System.Text.Encoding.Default.GetBytes(deviceIp);
            struLogInfo.sDeviceAddress = new byte[129];
            byIP.CopyTo(struLogInfo.sDeviceAddress, 0);

            //设备用户名
            byte[] byUserName = System.Text.Encoding.Default.GetBytes(userName);
            struLogInfo.sUserName = new byte[64];
            byUserName.CopyTo(struLogInfo.sUserName, 0);

            //设备密码
            byte[] byPassword = System.Text.Encoding.Default.GetBytes(password);
            struLogInfo.sPassword = new byte[64];
            byPassword.CopyTo(struLogInfo.sPassword, 0);

            struLogInfo.wPort = ushort.Parse(devicePort);//设备服务端口号

            struLogInfo.cbLoginResult = LoginCallBack;
            struLogInfo.bUseAsynLogin = false; //是否异步登录：0- 否，1- 是 

            if ((struLogInfo.bUseAsynLogin == true) && (LoginCallBack == null))
            {
                LoginCallBack = new CHCNetSDK.LOGINRESULTCALLBACK(cbLoginCallBack);//注册回调函数                    
            }

            struLogInfo.byLoginMode = 0; //0-Private, 1-ISAPI, 2-自适应
            struLogInfo.byHttps = 0; //0-不适用tls，1-使用tls 2-自适应

            CHCNetSDK.NET_DVR_DEVICEINFO_V40 DeviceInfo = new CHCNetSDK.NET_DVR_DEVICEINFO_V40();

            //登录设备 Login the device
            m_lUserID = CHCNetSDK.NET_DVR_Login_V40(ref struLogInfo, ref DeviceInfo);
            if (m_lUserID < 0)
            {
                iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                strErr = "NET_DVR_Login_V30 failed, error code= " + iLastErr; //登录失败，输出错误号 Failed to login and output the error code
                errMess = strErr;
                return false;
            }
            else
            {
                //登录成功
                iDeviceNumber++;
                string str1 = "" + m_lUserID;
                m_lUserIDList.Add(m_lUserID);
                deviceIpList.Add(deviceIp);
                deviceStatusList.Add("未布防");
                return true;
            }
        }

        /// <summary>
        /// 注销登录
        /// </summary>
        /// <returns></returns>
        public string Logout()
        {
            if (m_lUserID > 0)
            {
                //注销登录 Logout the device
                if (m_lRealHandle >= 0)
                {
                    //先停止预览
                    return "Please stop live view firstly";
                }

                if (!CHCNetSDK.NET_DVR_Logout(m_lUserID))
                {
                    iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    return "NET_DVR_Logout failed, error code= " + iLastErr;
                }
                m_lUserID = -1;
            }
            else
            {

            }
                return "";
        }

        /// <summary>
        /// 全部布防
        /// </summary>
        public bool SetAlarm(ref string errMess)
        {
            bool isSetAlarmSuccess = true;
            CHCNetSDK.NET_DVR_SETUPALARM_PARAM struAlarmParam = new CHCNetSDK.NET_DVR_SETUPALARM_PARAM();
            struAlarmParam.dwSize = (uint)Marshal.SizeOf(struAlarmParam);
            struAlarmParam.byLevel = 1; //0- 一级布防,1- 二级布防
            struAlarmParam.byAlarmInfoType = 1;//智能交通设备有效，新报警信息类型
            struAlarmParam.byFaceAlarmDetection = 1;//1-人脸侦测

            for (int i = 0; i < iDeviceNumber; i++)
            {
                m_lUserID = m_lUserIDList[i];
                m_lAlarmHandle[m_lUserID] = CHCNetSDK.NET_DVR_SetupAlarmChan_V41(m_lUserID, ref struAlarmParam);
                if (m_lAlarmHandle[m_lUserID] < 0)
                {
                    iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    strErr = "布防失败，错误号：" + iLastErr; //布防失败，输出错误号
                    errMess += "布防失败，错误号：" + iLastErr + "；";
                    deviceStatusList[i] = strErr;
                    isSetAlarmSuccess = false;
                }
                else
                {
                    deviceStatusList[i] = "布防成功";
                }
            }
            return isSetAlarmSuccess;
        }

        /// <summary>
        /// 全部撤防
        /// </summary>
        public bool CloseAlarm()
        {
            bool isCloseAlarmSuccess = true;
            for (int i = 0; i < iDeviceNumber; i++)
            {
                m_lUserID = m_lUserIDList[i];
                if (m_lAlarmHandle[m_lUserID] >= 0)
                {
                    if (!CHCNetSDK.NET_DVR_CloseAlarmChan_V30(m_lAlarmHandle[m_lUserID]))
                    {
                        iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                        strErr = "撤防失败，错误号：" + iLastErr; //撤防失败，输出错误号
                        deviceStatusList[i] = strErr;
                        isCloseAlarmSuccess = false;
                    }
                    else
                    {
                        deviceStatusList[i] = "未布防";
                        m_lAlarmHandle[i] = -1;
                    }
                }
                else
                {
                    deviceStatusList[i] = "未布防";
                }
            }
            return isCloseAlarmSuccess;
        }

        /// <summary>
        /// 开启监听
        /// </summary>
        /// <returns></returns>
        public bool StartListen(ref string errMess)
        {
            string sLocalIP = ListenIP;
            ushort wLocalPort = ushort.Parse(ListenPort);

            if (m_falarmData == null)
            {
                m_falarmData = new CHCNetSDK.MSGCallBack(MsgCallback);
            }

            iListenHandle = CHCNetSDK.NET_DVR_StartListen_V30(sLocalIP, wLocalPort, m_falarmData, IntPtr.Zero);
            if (iListenHandle < 0)
            {
                iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                errMess = "启动监听失败，错误号：" + iLastErr; //撤防失败，输出错误号
                return false;
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 停止监听
        /// </summary>
        /// <returns></returns>
        public string StopListen()
        {
            if (!CHCNetSDK.NET_DVR_StopListen_V30(iListenHandle))
            {
                iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                return "停止监听失败，错误号：" + iLastErr; //撤防失败，输出错误号
            }
            else
            {
                return "停止监听！";
            }
        }

        /// <summary>
        /// 开启预览
        /// </summary>
        /// <param name="RealPlayWnd"></param>
        /// <returns></returns>
        public bool LiveView(PictureBox RealPlayWnd, ref string errMess)
        {
            if (m_lUserID < 0)
            {
                errMess = "Please login the device firstly";
                return false;
            }

            if (m_lRealHandle < 0)
            {
                CHCNetSDK.NET_DVR_PREVIEWINFO lpPreviewInfo = new CHCNetSDK.NET_DVR_PREVIEWINFO();
                lpPreviewInfo.hPlayWnd = RealPlayWnd.Handle;//预览窗口
                lpPreviewInfo.lChannel = 1;//预te览的设备通道
                lpPreviewInfo.dwStreamType = 0;//码流类型：0-主码流，1-子码流，2-码流3，3-码流4，以此类推
                lpPreviewInfo.dwLinkMode = 0;//连接方式：0- TCP方式，1- UDP方式，2- 多播方式，3- RTP方式，4-RTP/RTSP，5-RSTP/HTTP 
                lpPreviewInfo.bBlocked = true; //0- 非阻塞取流，1- 阻塞取流
                lpPreviewInfo.dwDisplayBufNum = 1; //播放库播放缓冲区最大缓冲帧数
                lpPreviewInfo.byProtoType = 0;
                lpPreviewInfo.byPreviewMode = 0;

                if (SteamID != "")
                {
                    lpPreviewInfo.lChannel = -1;
                    byte[] byStreamID = System.Text.Encoding.Default.GetBytes(SteamID);
                    lpPreviewInfo.byStreamID = new byte[32];
                    byStreamID.CopyTo(lpPreviewInfo.byStreamID, 0);
                }


                if (RealData == null)
                {
                    RealData = new CHCNetSDK.REALDATACALLBACK(RealDataCallBack);//预览实时流回调函数
                }

                IntPtr pUser = new IntPtr();//用户数据

                //打开预览 Start live view 
                m_lRealHandle = CHCNetSDK.NET_DVR_RealPlay_V40(m_lUserID, ref lpPreviewInfo, null/*RealData*/, pUser);
                if (m_lRealHandle < 0)
                {
                    iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    errMess = "NET_DVR_RealPlay_V40 failed, error code= " + iLastErr; //预览失败，输出错误号
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 停止预览
        /// </summary>
        /// <returns></returns>
        public string StopLiveView()
        {
            if (m_lRealHandle > 0)
            {
                //停止预览 Stop live view 
                if (!CHCNetSDK.NET_DVR_StopRealPlay(m_lRealHandle))
                {
                    iLastErr = CHCNetSDK.NET_DVR_GetLastError();
                    return "NET_DVR_StopRealPlay failed, error code= " + iLastErr;
                }
                m_lRealHandle = -1;
            }else
            {

            }
            return "";
        }

        /// <summary>
        /// 自动重连
        /// </summary>
        public void AutoReconnect()
        {
            IsReconnectCheck = true;
            System.Threading.Tasks.Task.Run(() =>
            {
                while (IsReconnectCheck)
                {
                    if (!IsConnection)
                    {
                        LogObj.Error(ExceptionType.InterfaceException, new Exception("红外相机未正常打开，尝试重新打开"));
                        OnConnectionBreak?.BeginInvoke("红外相机", null, null);
                        //Login();
                        continue;
                    }
                    Thread.Sleep(2000);
                }
            });
        }

        public void RealDataCallBack(Int32 lRealHandle, UInt32 dwDataType, IntPtr pBuffer, UInt32 dwBufSize, IntPtr pUser)
        {
            if (dwBufSize > 0)
            {
                byte[] sData = new byte[dwBufSize];
                Marshal.Copy(pBuffer, sData, 0, (Int32)dwBufSize);

                string str = "实时流数据.ps";
                FileStream fs = new FileStream(str, FileMode.Create);
                int iLen = (int)dwBufSize;
                fs.Write(sData, 0, iLen);
                fs.Close();
            }
        }

        /// <summary>
        /// 关闭所有连接
        /// </summary>
        public void Exit()
        {
            //撤防
            CloseAlarm();

            //停止监听
            if (iListenHandle >= 0)
            {
                CHCNetSDK.NET_DVR_StopListen_V30(iListenHandle);
            }

            //注销登录
            for (int i = 0; i < iDeviceNumber; i++)
            {
                m_lUserID = m_lUserIDList[i];
                CHCNetSDK.NET_DVR_Logout(m_lUserID);
            }

            //释放SDK资源，在程序结束之前调用
            CHCNetSDK.NET_DVR_Cleanup();
        }

        public void UpdateClientListException(DateTime AlarmTime, int lUserID, string strAlarmMsg)
        {
            //异常设备信息
            string strDevIP = "";
            for (int i = 0; i < iDeviceNumber; i++)
            {
                m_lUserID = m_lUserIDList[i];
                if (m_lUserID == lUserID)
                {
                    strDevIP = deviceIpList[i];
                }
            }
            //集合新增报警信息
            GolbalVariable.NoticInfoBag.Add(new NoticInfoModel { NoticTime = AlarmTime, NoticMsg = strAlarmMsg });
        }

        public void cbExceptionCB(uint dwType, int lUserID, int lHandle, IntPtr pUser)
        {
            //异常消息信息类型
            string stringAlarm = "异常消息回调，信息类型：0x" + Convert.ToString(dwType, 16) + ", lUserID:" + lUserID + ", lHandle:" + lHandle;

            if(Convert.ToString(dwType, 16) == "8005")
            {
                OnConnectionBreak?.BeginInvoke("相机异常", null, null);
            }
            UpdateClientListException(DateTime.Now, lUserID, stringAlarm);
        }

        public bool MsgCallback_V31(int lCommand, ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
        {
            //通过lCommand来判断接收到的报警信息类型，不同的lCommand对应不同的pAlarmInfo内容
            AlarmMessageHandle(lCommand, ref pAlarmer, pAlarmInfo, dwBufLen, pUser);

            return true; //回调函数需要有返回，表示正常接收到数据
        }

        public void MsgCallback(int lCommand, ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
        {
            //通过lCommand来判断接收到的报警信息类型，不同的lCommand对应不同的pAlarmInfo内容
            AlarmMessageHandle(lCommand, ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
        }

        public void AlarmMessageHandle(int lCommand, ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
        {
            //通过lCommand来判断接收到的报警信息类型，不同的lCommand对应不同的pAlarmInfo内容
            switch (lCommand)
            {
                case CHCNetSDK.COMM_ALARM: //(DS-8000老设备)移动侦测、视频丢失、遮挡、IO信号量等报警信息
                    //ProcessCommAlarm(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                case CHCNetSDK.COMM_ALARM_V30://移动侦测、视频丢失、遮挡、IO信号量等报警信息
                    //ProcessCommAlarm_V30(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                case CHCNetSDK.COMM_ALARM_RULE://进出区域、入侵、徘徊、人员聚集等行为分析报警信息
                    //ProcessCommAlarm_RULE(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                case CHCNetSDK.COMM_UPLOAD_PLATE_RESULT://交通抓拍结果上传(老报警信息类型)
                    //ProcessCommAlarm_Plate(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                case CHCNetSDK.COMM_ITS_PLATE_RESULT://交通抓拍结果上传(新报警信息类型)
                    //ProcessCommAlarm_ITSPlate(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                case CHCNetSDK.COMM_ALARM_TPS_REAL_TIME://交通抓拍结果上传(新报警信息类型)
                    //ProcessCommAlarm_TPSRealInfo(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                case CHCNetSDK.COMM_ALARM_TPS_STATISTICS://交通抓拍结果上传(新报警信息类型)
                    //ProcessCommAlarm_TPSStatInfo(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                case CHCNetSDK.COMM_ALARM_PDC://客流量统计报警信息
                    //ProcessCommAlarm_PDC(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                case CHCNetSDK.COMM_ITS_PARK_VEHICLE://客流量统计报警信息
                    //ProcessCommAlarm_PARK(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                case CHCNetSDK.COMM_DIAGNOSIS_UPLOAD://VQD报警信息
                    //ProcessCommAlarm_VQD(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                case CHCNetSDK.COMM_UPLOAD_FACESNAP_RESULT://人脸抓拍结果信息
                    //ProcessCommAlarm_FaceSnap(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                case CHCNetSDK.COMM_SNAP_MATCH_ALARM://人脸比对结果信息
                    //ProcessCommAlarm_FaceMatch(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                case CHCNetSDK.COMM_ALARM_FACE_DETECTION://人脸侦测报警信息
                    //ProcessCommAlarm_FaceDetect(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                case CHCNetSDK.COMM_ALARMHOST_CID_ALARM://报警主机CID报警上传
                    //ProcessCommAlarm_CIDAlarm(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                case CHCNetSDK.COMM_UPLOAD_VIDEO_INTERCOM_EVENT://可视对讲事件记录信息
                    //ProcessCommAlarm_InterComEvent(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                case CHCNetSDK.COMM_ALARM_ACS://门禁主机报警上传
                    //ProcessCommAlarm_AcsAlarm(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                case CHCNetSDK.COMM_ID_INFO_ALARM://身份证刷卡信息上传
                    //ProcessCommAlarm_IDInfoAlarm(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                case CHCNetSDK.COMM_UPLOAD_AIOP_VIDEO://设备支持AI开放平台接入，上传视频检测数据
                    //ProcessCommAlarm_AIOPVideo(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                case CHCNetSDK.COMM_UPLOAD_AIOP_PICTURE://设备支持AI开放平台接入，上传图片检测数据
                    //ProcessCommAlarm_AIOPPicture(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                case CHCNetSDK.COMM_ISAPI_ALARM://ISAPI报警信息上传
                    //ProcessCommAlarm_ISAPIAlarm(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                case CHCNetSDK.COMM_THERMOMETRY_ALARM://温度报警信息
                    ProcessCommAlarm_ThermAlarm(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
                    break;
                default:
                    {
                        //报警设备IP地址
                        string strIP = System.Text.Encoding.UTF8.GetString(pAlarmer.sDeviceIP).TrimEnd('\0');
                        //报警信息类型
                        string stringAlarm = "报警上传，信息类型：0x" + Convert.ToString(lCommand, 16);
                    }
                    break;
            }
        }

        string timeStamp;
        string filePath;
        string fileName;
        private void ProcessCommAlarm_ThermAlarm(ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
        {
            CHCNetSDK.NET_DVR_THERMOMETRY_ALARM struThermAlarm = new CHCNetSDK.NET_DVR_THERMOMETRY_ALARM();
            uint dwSize = (uint)Marshal.SizeOf(struThermAlarm);
            struThermAlarm = (CHCNetSDK.NET_DVR_THERMOMETRY_ALARM)Marshal.PtrToStructure(pAlarmInfo, typeof(CHCNetSDK.NET_DVR_THERMOMETRY_ALARM));
            //报警设备IP地址
            string strIP = System.Text.Encoding.UTF8.GetString(pAlarmer.sDeviceIP).TrimEnd('\0');
            //保存热成像图片数据
            if ((struThermAlarm.dwThermalPicLen != 0) && (struThermAlarm.pThermalPicBuff != IntPtr.Zero))
            {
                timeStamp = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                filePath = DateTime.Now.ToString("yyyyMMdd");
                //string strPath = ".\\picture\\" + filePath + "\\";
                //DirFileHelper.CreateDirectory(strPath);
                fileName = "ThermalPicBuff_" + timeStamp + ".jpg";
                //FileStream fs = new FileStream(strPath + fileName, FileMode.Create);
                int iLen = (int)struThermAlarm.dwThermalPicLen;
                byte[] by = new byte[iLen];
                Marshal.Copy(struThermAlarm.pThermalPicBuff, by, 0, iLen);
                iFileNumber++;
                string stringAlarm = "实时测温信息，区域ID:" + struThermAlarm.byRuleID + "测温单位：" + struThermAlarm.byThermometryUnit + "，测温类型：" + struThermAlarm.byAlarmType
                    + "，规则类型：" + struThermAlarm.byRuleCalibType + "，当前温度：" + struThermAlarm.fCurrTemperature;
                UpdateClientList(DateTime.Now, strIP, stringAlarm, struThermAlarm.fCurrTemperature, struThermAlarm.byRuleID.ToString(), filePath, fileName, by, iLen);
            }
        }

        public void UpdateClientList(DateTime AlarmTime, string strDevIP, string strAlarmMsg, float fCurrTemperature, string strRegion, string filePath, string fileName, byte[] by, int iLen)
        {
            AlarmInfoModel model = new AlarmInfoModel
            {
                AlarmTime = AlarmTime,
                DevIP = strDevIP,
                AlarmMsg = strAlarmMsg,
                fCurrTemperature = fCurrTemperature,
                IsRegionOK = false,
                Region = strRegion,
                PictureName = filePath + "\\" + fileName,
                FilePath = filePath,
                FileName = fileName,
                Byt = by,
                ILen = iLen
            };
            DataReceiverEvent?.BeginInvoke(model,null,null);
        }

        public void cbLoginCallBack(int lUserID, int dwResult, IntPtr lpDeviceInfo, IntPtr pUser)
        {
            string strLoginCallBack = "登录设备，lUserID：" + lUserID + "，dwResult：" + dwResult;

            if (dwResult == 0)
            {
                uint iErrCode = CHCNetSDK.NET_DVR_GetLastError();
                strLoginCallBack = strLoginCallBack + "，错误号:" + iErrCode;
            }
        }
    }
}
